package com.xiaoyu.merchant.ui.fragment.order;


import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.xiaoyu.commonlib.network.CommonHttpResponser;
import com.xiaoyu.commonlib.ui.adapter.AllPowerfulAdapter;
import com.xiaoyu.commonlib.ui.base.BaseFragment;
import com.xiaoyu.commonlib.utils.PreferencesUtil;
import com.xiaoyu.commonlib.utils.ToastUtil;
import com.xiaoyu.merchant.R;
import com.xiaoyu.merchant.model.OrderBean;
import com.xiaoyu.merchant.network.NetworkManager;
import com.xiaoyu.merchant.ui.activity.order.AfterProcessingActivity;
import com.xiaoyu.merchant.ui.activity.order.CheckOrderActivity;
import com.xiaoyu.merchant.ui.activity.order.ShipMentsActivity;
import com.xiaoyu.merchant.ui.activity.order.WaitGoodsActivity;
import com.xiaoyu.merchant.ui.activity.order.WaitPaymentActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;


/**
 * @author jx
 * @date 创建时间 2018/12/29
 * @Description 我的订单中五个fragment
 */
@SuppressLint("ResourceAsColor")
public class OrderFragment extends BaseFragment {

    public static final String ORDER_ID = "order_id";
    @BindView(R.id.smart_refresh_layout)
    SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.common_recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R.id.common_recycler_view_empty_page)
    ImageView mEmptyImg;
    public static final String ARG_PARAM = "param";
    private String mParam;
    private View mView;
    private AllPowerfulAdapter mOrderAdapter;
    private List<OrderBean.DataBean.ListBean> mOrderList = new ArrayList<>();
    private String state;//订单状态 1未付款，2待发货，3待收货，4待评价，5已评价，6订单售后处理，7售后完成，8订单完成
    private int page = 1;
    private int totalPage;

    public OrderFragment newInstance(String param) {
        OrderFragment fragment = new OrderFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM, param);
        fragment.setArguments(args);
        return fragment;
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (mView == null) {
            mView = inflater.inflate(R.layout.common_recycler_view, container, false);
            ButterKnife.bind(this, mView);
            initView();
        }
        return mView;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam = getArguments().getString(ARG_PARAM);
        }
        if (mParam.equals("order0")) {
            state = "1";
        } else if (mParam.equals("order1")) {
            state = "2";
        } else if (mParam.equals("order2")) {
            state = "3";
        } else if (mParam.equals("order3")) {
            state = "5";
        } else if (mParam.equals("order4")) {
            state = "8";
        }
    }

    private void initView() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.setBackgroundColor(getResources().getColor(R.color.color_gray_F3));

        setObligationAdapter(mOrderList);
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @NonNull
            @Override
            public RefreshFooter createRefreshFooter(@NonNull Context context, @NonNull RefreshLayout layout) {
                return new ClassicsFooter(context).setDrawableSize(20);
            }
        });
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @NonNull
            @Override
            public RefreshHeader createRefreshHeader(@NonNull Context context, @NonNull RefreshLayout layout) {
                return new ClassicsHeader(context).setDrawableSize(20);
            }
        });
        mRefreshLayout.setOnRefreshListener(onRefreshListener);
        mRefreshLayout.setOnLoadMoreListener(onLoadMoreListener);
    }

    @Override
    public void onResume() {
        super.onResume();
        page = 1;
        mOrderList.clear();
        getOrderList();
    }

    /**
     * 获取订单列表 -- 根据订单状态
     */
    private void getOrderList() {
        NetworkManager.orderList(PreferencesUtil.getString(PreferencesUtil.TOKEN, ""), state, page, new CommonHttpResponser() {
            @Override
            public void onSuccess(String result) {
                parseOrderInfoSuc(result);
            }

            @Override
            public void onFailed(String errorCode, String errorDiscription) {
            }
        });
    }

    private void parseOrderInfoSuc(String result) {
        if (page == 1) {
            mOrderList.clear();
        }
        OrderBean bean = new Gson().fromJson(result, OrderBean.class);
        totalPage = Integer.parseInt(bean.getData().getCount());
        mOrderList.addAll(bean.getData().getList());
        if (mOrderList.size() == 0) {
            mRecyclerView.setVisibility(View.GONE);
            mEmptyImg.setVisibility(View.VISIBLE);
            mEmptyImg.setImageResource(R.mipmap.order_empty);
        }
        mOrderAdapter.notifyDataSetChanged();
        if (totalPage <= 1) {
            mRefreshLayout.setEnableLoadMore(false);
        } else {
            mRefreshLayout.setEnableLoadMore(true);
        }
    }

    //设置适配器
    private void setObligationAdapter(List<OrderBean.DataBean.ListBean> mOrderList) {
        mOrderAdapter = new AllPowerfulAdapter<OrderBean.DataBean.ListBean>(R.layout.my_order_item, mOrderList) {
            @Override
            protected void convert(BaseViewHolder baseViewHolder, OrderBean.DataBean.ListBean orderParam) {
                super.convert(baseViewHolder, orderParam);

                ImageView goodsdeimg = baseViewHolder.getView(R.id.collect_shop_item_img);
                Glide.with(getActivity()).load(orderParam.getGoodsdeimg()).into(goodsdeimg);//商品展示图
                baseViewHolder.setText(R.id.collect_order_item_explain, orderParam.getGoodsname());//商品名字
                baseViewHolder.setText(R.id.collect_order_item_model, orderParam.getGoodsdetailsname());//规格
                baseViewHolder.setText(R.id.collect_order_item_sprice, "¥   " + orderParam.getGoodsprice());//商品单价
                baseViewHolder.setText(R.id.collect_order_item_num, "共" + orderParam.getGoodsnumber() + "件商品       合计：¥  " + orderParam.getOrdermoney());

                RelativeLayout mRelativeItem = baseViewHolder.getView(R.id.my_order_item_relative);
                TextView payment = baseViewHolder.getView(R.id.payment);
                setItem(mRelativeItem, payment, orderParam);
            }
        };
        mRecyclerView.setAdapter(mOrderAdapter);
    }

    private void setItem(final RelativeLayout mRelativeItem, final TextView mPayment, final OrderBean.DataBean.ListBean orderParam) {
        if (mParam.equals("order0")) {//待付款
            mPayment.setText("等待付款");
            mPayment.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(), WaitPaymentActivity.class);
                    intent.putExtra(ORDER_ID, orderParam.getOrderid());//订单id
                    startActivity(intent);
                }
            });
            mRelativeItem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //TODO:点击进入详情
                }
            });
        }
        if (mParam.equals("order1")) {//待发货
            mPayment.setText("发货");
            mPayment.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(), ShipMentsActivity.class);
                    intent.putExtra(ORDER_ID, orderParam.getOrderid());//订单id
                    startActivity(intent);
                }
            });
            mRelativeItem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //TODO:点击进入详情
                }
            });
        }
        if (mParam.equals("order2")) {//待收货
            mPayment.setText("等待收货");
            mPayment.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(), WaitGoodsActivity.class);
                    intent.putExtra(ORDER_ID, orderParam.getOrderid());//订单id
                    startActivity(intent);
                }
            });
            mRelativeItem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //TODO:点击进入详情
                }
            });
        }
        if (mParam.equals("order3")) {//售后
            mPayment.setText("处理");
            mPayment.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(), AfterProcessingActivity.class);
                    intent.putExtra(ORDER_ID, orderParam.getOrderid());//订单id
                    startActivity(intent);
                }
            });
            mRelativeItem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //TODO:点击进入详情
                }
            });
        }
        if (mParam.equals("order4")) {//已完成
            mPayment.setText("查看订单");
            mPayment.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(), CheckOrderActivity.class);
                    intent.putExtra(ORDER_ID, orderParam.getOrderid());//订单id
                    startActivity(intent);
                }
            });
            mRelativeItem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //TODO:点击进入详情
                }
            });
        }
    }


    /**
     * 数据刷新
     */
    private OnRefreshListener onRefreshListener = new OnRefreshListener() {
        @Override
        public void onRefresh(@NonNull RefreshLayout refreshLayout) {
            page = 1;
            mOrderList.clear();
            mOrderAdapter.notifyDataSetChanged();
            getOrderList();
            mRefreshLayout.finishRefresh();
            mRefreshLayout.setNoMoreData(false);
        }
    };


    /**
     * 加载更多
     */
    private OnLoadMoreListener onLoadMoreListener = new OnLoadMoreListener() {
        @Override
        public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
            if (page < totalPage) {
                page = page + 1;
                getOrderList();
                mRefreshLayout.finishLoadMore();
                mRefreshLayout.setNoMoreData(true);
            } else {
                ToastUtil.showToast(getActivity(), "已经没有更多数据！");
                mRefreshLayout.finishLoadMore();
                mRefreshLayout.setNoMoreData(false);
                mRefreshLayout.finishLoadMoreWithNoMoreData();
            }
        }
    };
}